<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="不良品单号" prop="code">
          <CodeRuleInput :band-value.sync="formData.code" table-name="quality_disqualification_dispose" column-name="code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="处理人员">
          <el-input v-model="formData.disposeName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="处理日期" prop="disposeDate">
          <el-date-picker
            v-model="formData.disposeDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item v-if="!isShowDisabled" label="不良品来源" prop="sourceCode">
          <!--          <DictSelect-->
          <!--            :band-value.sync="formData.sourceCode"-->
          <!--            dict-type="sourceCode"-->
          <!--          />-->
          <el-select
            v-model="formData.sourceCode"
            clearable
            filterable
            style="width:100%"
            placeholder="请选择"
          >
            <el-option
              v-for="item in sourceCodeList"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-else label="不良品来源" prop="sourceCode">
          <el-input v-model="formData.sourceCodeName" disabled />
        </el-form-item>
        <el-form-item label="关联表单">
          <el-input v-model="formData.relatedCheckCode" disabled />
        </el-form-item>
        <el-form-item v-if="!isShowDisabled" label="物料编码" class="clickChoose" prop="materialCode">
          <el-input v-model="formData.materialCode" placeholder="请选择" readonly />
          <a
            class="clickChoose_button"
            @click.prevent="chooseMaterial"
          >
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item v-else label="物料编码" class="clickChoose" prop="materialCode">
          <el-input v-model="formData.materialCode" placeholder="请选择" disabled readonly />
          <!--          <a-->
          <!--            class="clickChoose_button"-->
          <!--          >-->
          <!--            <svg-icon icon-class="选择弹框" />-->
          <!--          </a>-->
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="formData.materialName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input v-model="formData.materialModel" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="物料单位">
          <el-input v-model="formData.materialUnitName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="不良数量" prop="disqualificationNumber">
          <el-input v-model="formData.disqualificationNumber" placeholder="暂无" :disabled="isShowDisabled" />
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.url"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            maxlength="200"
            show-word-limit
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        不良处理
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="addRow">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="deleteRow">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div ref="table_container2" class="table_container draggableTable">
        <el-table
          ref="table"
          :data="listData"
          :height="tableHeight"
          stripe
          border
          style="width: 99.9%"
          :header-cell-class-name="headerCellClassName"
          @selection-change="selectionChange"
        >
          <el-table-column
            type="selection"
            width="70"
            align="center"
          />
          <el-table-column label="处置方式" width="180" prop="disposeWayStatus">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.disposeWayStatus"
                clearable
                filterable
                style="width:100%"
                placeholder="请选择"
                @input="getDisposeStatus($event,scope.row)"
              >
                <el-option
                  v-for="item in taxRateCodeList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="处置数量" width="180" prop="disposeNumber">
            <template slot-scope="scope">
              <el-input v-model="scope.row.disposeNumber" placeholder="请输入" clearable />
            </template>
          </el-table-column>
          <el-table-column label="工序" width="180" prop="engineeringProcessId">
            <template slot-scope="scope">
              <el-select
                v-if="isShow == '0'"
                v-model="scope.row.engineeringProcessId"
                :disabled="scope.row.isDisposeWayCode"
                clearable
                filterable
                style="width:100%"
                :placeholder="scope.row.isDisposeWayCode?'暂无':'请选择'"
                @change="getengineeringProcess(scope.row)"
                @input="getIsStatus($event,scope.row)"
              >
                <el-option
                  v-for="item in engineeringProcessList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                v-else
                v-model="scope.row.engineeringRequirementMaterialId"
                :disabled="scope.row.isDisposeWayCode"
                clearable
                filterable
                style="width:100%"
                :placeholder="scope.row.isDisposeWayCode?'暂无':'请选择'"
                @change="getengineeringProcess(scope.row)"
                @input="getIsStatus($event, scope.row)"
              >
                <el-option
                  v-for="item in engineeringProcessList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="save">保存</el-button>
      <el-button @click.stop="onSubmit">提交</el-button>
    </div>
  </div>
</template>

<script>
import { disqualificationAddOrUpdate, disqualificationGetInfo, getEngineeringRequirements } from '@/api/qualityManage/rejectsDispose'
import { list } from '@/api/purchaseManage/supplierInfo'
import { list as processList } from '@/api/engineeringManage/processManage'
import chooseMaterial from '@/views/warehouseManagement/materialInfo/addMaterialInfoOne'
import moment from 'moment'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    show: {}
  },
  data() {
    const disqualificationNumber = (rule, value, callback) => {
      console.log(value)
      if (!value) {
        callback(new Error('不良数量不能为空'))
      } else if (value && !this.SETTINGS.reg_no_zero.test(this.formData.disqualificationNumber)) {
        callback(new Error('不良数量填写不正确'))
      } else {
        callback()
      }
    }
    return {
      formData: {
        id: '',
        materialInformationId: '',
        materialCode: '',
        disposeName: '',
        fileName: '',
        fileRealName: '',
        url: '',
        materialModel: '',
        materialTypeName: '',
        materialUnitName: '',
        disposeDate: '',
        relatedCheckId: '',
        isForWork: '',
        sourceCode: '',
        sourceCodeName: '',
        data: [],
        status: '1',
        spotCheckNumber: '',
        isAllProcess: ''
      },
      pageData: {
        pageNum: 1,
        pageSize: 9999,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      isDisposeWayCode: false,
      tableHeight: '400',
      isShow: '0',
      supplierData: [],
      selectionsAll: [],
      engineeringProcessList: [],
      isShowDisabled: false,
      taxRateCodeList: [
        { id: '0', label: '报废' },
        { id: '1', label: '返工' }
      ],
      sourceCodeList: [
        { id: '1', label: '生产不良' },
        { id: '2', label: '首件不良' }
      ],
      peopleList: [],
      listData: [],
      selectionData: [],
      MaterialList: [],
      rules: {
        materialCode: [
          { required: true, message: '物料编码不能为空', trigger: 'change' }
        ],
        code: [
          { required: true, message: '不良品单号不能为空', trigger: 'blur' }
        ],
        disqualificationNumber: [
          { validator: disqualificationNumber, trigger: 'change', required: true }
        ]
      }
    }
  },
  created() {
    if (!this.id) { // 没有id就是新增
      this.formData.disposeName = this.$store.state.user.name
      this.formData.disposeBy = this.$store.state.user.userId
      this.formData.disposeDate = moment(new Date()).format('YYYY-MM-DD')
      this.getProcessList()
    } else { // 有id就是编辑
      this.getInfo()
    }
    if (this.show) {
      this.isShowDisabled = this.show
    }
    this.getList()
  },
  mounted() {
  },
  methods: {
    setFileName(...data) {
      this.$set(this.formData, 'fileName', data[0])
      this.$set(this.formData, 'fileRealName', data[1])
      this.$set(this.formData, 'url', data[2])
    },
    headerCellClassName(data) {
      if (['disposeNumber', 'engineeringProcessId', 'disposeWayStatus'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    getIsStatus(e, row) {
      if (!e) {
        row.engineeringProcessId = ''
        row.engineeringProcessName = ''
        row.engineeringRequirementMaterialId = ''
      }
    },
    getengineeringProcess(row) {
      const arr = this.engineeringProcessList.filter(item => {
        return item.id == row.engineeringProcessId || item.id == row.engineeringRequirementMaterialId
      })
      arr.filter(ele => {
        row.engineeringProcessName = ele.label
      })
    },
    getProcessList() {
      if (this.formData.isAllProcess == '1') {
        this.isShow = '0'
        processList(this.pageData).then(res => {
          res.data.forEach(item => {
            item['value'] = item.id
            item['label'] = item.name
          })
          this.engineeringProcessList = res.data
        })
      } else {
        if (this.formData.relatedCheckCode && this.formData.relatedCheckAutomaticCreate == '1') {
          this.isShow = '1'
          getEngineeringRequirements({ relatedCheckId: this.formData.relatedCheckId, isForWork: this.formData.isForWork, sourceCode: this.formData.sourceCode }).then(res => {
            res.data.forEach(item => {
              item['value'] = item.id
              item['label'] = item.engineeringProcessName
            })
            this.engineeringProcessList = res.data
          })
        } else {
          this.isShow = '0'
          processList(this.pageData).then(res => {
            res.data.forEach(item => {
              item['value'] = item.id
              item['label'] = item.name
            })
            this.engineeringProcessList = res.data
          })
        }
      }
    },
    getInfo() {
      disqualificationGetInfo(this.id).then(res => {
        this.formData = res.data
        this.listData = res.data.data
        if (this.listData) {
          this.listData.forEach(ele => {
            this.selectionData.push(ele.customerId)
          })
        }
        if (!this.formData.disposeName) {
          this.formData.disposeName = this.$store.state.user.name
          this.formData.disposeBy = this.$store.state.user.userId
        }
        if (!this.formData.disposeDate && this.show) {
          this.formData.disposeDate = moment(new Date()).format('YYYY-MM-DD')
        }
        this.getProcessList()
      })
    },
    getDisposeStatus(e, row) {
      if (!e) {
        row.engineeringProcessId = ''
        row.engineeringProcessName = ''
        row.engineeringRequirementMaterialId = ''
        row.isDisposeWayCode = false
      } else if (e == 0) {
        row.isDisposeWayCode = true
        if (row.engineeringProcessId || row.engineeringRequirementMaterialId) {
          row.engineeringProcessId = ''
          row.engineeringProcessName = ''
          row.engineeringRequirementMaterialId = ''
        }
      } else {
        row.isDisposeWayCode = false
        if (this.formData.relatedCheckId) {
          getEngineeringRequirements({ relatedCheckId: this.formData.relatedCheckId, isForWork: this.formData.isForWork, sourceCode: this.formData.sourceCode }).then(res => {
            res.data.forEach(item => {
              item['value'] = item.id
              item['label'] = item.engineeringProcessName
            })
            this.engineeringProcessList = res.data
          })
        }
      }
    },
    getList() {
      list(this.pageData).then(res => {
        this.peopleList = res.data
      })
    },
    addRow() {
      const obj = {
        disposeWayStatus: '',
        disposeNumber: '',
        engineeringProcessId: '',
        engineeringRequirementMaterialId: ''
      }
      this.listData.push(obj)
    },
    selectionChange(row) {
      this.selectionsAll = row
    },
    deleteRow() {
      this.selectionsAll.forEach(item => {
        this.listData.splice(this.listData.indexOf(item), 1)
      })
    },
    showMaterial(row) {
      this.formData.materialId = row.id
      this.formData.materialCode = row.materialCode
      this.formData.materialName = row.materialName
      this.formData.materialModel = row.materialModel
      this.formData.materialUnitName = row.materialUnitName
    },
    chooseMaterial() {
      const MaterialData = this.$deepClone(this.formData)
      this.MaterialList.push(MaterialData)
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseMaterial, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            materialId: this.formData.materialId ? this.formData.materialId : ''
          } // props
        },
        area: ['1000px', '700px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 保存
    save() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.listData.filter(item => item).length < 0) {
            this.formData.status = '0'
          } else {
            this.formData.status = '1'
          }
          this.formData.data = this.listData
          if (this.formData.disposeDate == null) {
            this.formData.disposeDate = ''
          }
          disqualificationAddOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    // 提交
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.listData.filter(item => item).length <= 0) {
            this.$message.warning('请添加不良处理')
            return
          } else if (this.listData.filter(item => !item.disposeWayStatus).length > 0) {
            this.$message.warning('处置方式不能为空')
            return
          } else if (this.listData.filter(item => !item.disposeNumber).length > 0) {
            this.$message.warning('处置数量不能为空')
            return
          } else if (this.listData.filter(item => item.disposeNumber && !this.SETTINGS.reg_no_zero.test(item.disposeNumber)).length > 0) {
            this.$message.warning('处置数量未正确填写')
            return
          }
          if (this.formData.isRequired == '1') {
            if (this.listData.filter(item => item.disposeWayStatus == '1' && !item.engineeringProcessName).length > 0) {
              this.$message.warning('工序不能为空')
              return
            }
          }
          this.formData.data = this.listData
          const SumNumber = this.listData.reduce((total, g) => {
            return total + Number(g.disposeNumber)
          }, 0)
          console.log(SumNumber)
          if (SumNumber != this.formData.disqualificationNumber) {
            this.$message.warning('处置数量之和要等于不良数量！')
            return
          }
          if (this.formData.disposeDate == null) {
            this.formData.disposeDate = ''
          }
          disqualificationAddOrUpdate({
            ...this.formData,
            status: '2'
          }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-table__empty-block {
  position: absolute !important;
  left: 30%;
}
.title {
  padding-left: 10px;
  padding-bottom: 20px;
  font-size: 24px;
  width: 100%;
}
.record_bottom {
  justify-content: space-between;
  h2 {
    flex: 1;
  }
}
.el-input{
  width: 100% !important;
}
/deep/.el-table__header {
  width: 100% !important;
}
/deep/ .el-table__body {
  width: 100% !important;
}
</style>
